'use strict';
(function(){
    var localVedio, localStream, wsSocket;
    var wsNews = window.WebSocket || window.MozWebSocket;
    var isConn = false;
    var roomId = "1";
    var clientId = "1";
    var pcs    = {};
    var config = {"iceServers": [{"urls":"stun:stun.l.google.com:19302"}]};
    var wsUri  ="ws://121.42.212.167:8089/ws";
    localVedio = document.getElementById('localVideo');
    localVedio.addEventListener('loadedmetadata', function() {
        console.log('Local video videoWidth: ' + this.videoWidth + 'px,  videoHeight: ' + this.videoHeight + 'px');
    });
    navigator.mediaDevices.getUserMedia({audio: true, video: true}).then(function(stream){
        localVedio.srcObject = stream;
        localStream          = stream;
    }).catch(function(e) {
        console.log('getUserMedia() error: ' + e.name);
    });
    if (!wsNews) {
        console.log('websocket not support');
    } else {
        wsSocket = new wsNews(wsUri);
        wsSocket.onopen = function() {
            console.log("connected");
            isConn  = true;
            register(roomId, clientId);
        };
        wsSocket.onerror = function(err) {
            console.log(err);
        };
        wsSocket.onclose = function(){
            console.log("client close!");
        };
        wsSocket.onmessage = function(evt){
            wsRecv(evt.data);
        };
    };

    function wsRecv(data) {
       console.log("origin1:"+data);
        var obj  = JSON.parse(data);
        if (obj.error != "") {
            console.log("error=="+obj.error);
            return;
        };
        console.log("origin2:"+data);
        var message = JSON.parse(obj.msg);
        console.log("msg==============="+message.Cmd);
        if (message.Cmd == "START") {
            newDiald(message.cliidme);
            return;
        };

        var cliid = message.cliidme;
    
        if ( pcs[cliid] && message.desc) {
            var desc = message.desc;
            // if we get an offer, we need to reply with an answer
            if (desc.type == "offer") {
                 pcs[cliid].setRemoteDescription(new RTCSessionDescription(desc)).then(function () {
                    return  pcs[cliid].createAnswer();
                }).then(function (answer) {
                    return  pcs[cliid].setLocalDescription(answer);
                }).then(function () {
                    wsSend(roomId, clientId, message.clientid, {"desc": pcs[cliid].localDescription});
                }).catch(function(err){
                    console.log(err);
                });
            } else {
                 pcs[cliid].setRemoteDescription(new RTCSessionDescription(desc)).catch(function(err){
                    console.log(err);
                });
            }
        }
     /*   if (pcs[cliid] && message.candidate) {
            console.log("addIceCandidate:"+message);
            pc.addIceCandidate(new RTCIceCandidate(message)).catch(function(err){
                console.log(err);
            });
        }*/

         else {
            console.log("addIceCandidate:"+message.candidate);
             pcs[cliid].addIceCandidate(new RTCIceCandidate(message)).catch(function(err){
                console.log(err);
            });
        }
    };

    function wsSend(roomid, mclientid, cliid, msg) {
       console.log("send to server", roomid, mclientid, cliid, msg);
        msg.cliidme = mclientid;
        var data = {"Cmd":"private", "RoomID":roomid, "ClientID":cliid, "Msg":JSON.stringify(msg)};
        if (isConn) {
            wsSocket.send(JSON.stringify(data));
        } else {
            console.log("send websocket error!");
        }
    };

   function newDiald(cliid) {
        console.log("diald client:"+cliid);
        if (pcs[cliid]) {
            pcs[cliid].close();
            pcs[cliid] = null;
        };
        pcs[cliid] = new RTCPeerConnection(config);
        console.log("diald client:"+pcs[cliid]);
        // send any ice candidates to the other peer
        pcs[cliid].onicecandidate = function (evt) {
            console.log("onicecandidate:"+evt);
            if (evt.candidate) {
                wsSend(roomId, clientId, cliid, {"label":evt.candidate.sdpMLineIndex,"candidate":evt.candidate.candidate});
            }
        };
        // let the "negotiationneeded" event trigger offer generation
       pcs[cliid].onnegotiationneeded = function (evt) {
            console.log("onnegotiationneeded:"+evt);
            pcs[cliid].createOffer().then(function (offer) {
                return pcs[cliid].setLocalDescription(offer);
            }).then(function () {
                // send the offer to the other peer
                wsSend(roomId, clientId, cliid, {"desc":pcs[cliid].localDescription});
            }).catch(function(err){
                console.log(err);
            });
        }; /**/

       
        pcs[cliid].addStream(localStream);
        console.log("localStream add queue" + pcs[cliid]);
        console.log(localStream);
    };

    function register(roomid, clientid) {
        var data = {"Cmd":"register", "RoomID":roomid, "ClientID":clientid, "Msg":""};
        if (isConn) {
            wsSocket.send(JSON.stringify(data));
        } else {
            console.log("register websocket error!");
        }
    };
})();
